package com.jspsmart.upload;

import java.util.StringTokenizer;

import javax.servlet.jsp.PageContext;

public class FileUtil { 
	private static String getFileExtName(String strFileName) {
		//取得不带后缀的文件名 
		//String  suffix=myFileName.substring(0,myFileName.lastIndexOf('.')); 
		StringTokenizer token = new StringTokenizer(strFileName, ".");
		String extName = "";
		while (token.hasMoreElements()) {
			extName = token.nextToken();
		}
		return extName;
	}

	public static boolean blInArray(String[] sa, String s) {
		for (int i = 0; i < sa.length; i++) {
			if (s.equalsIgnoreCase(sa[i]))
				return true;
		}
		return false; 
	}

	public String Upload(PageContext pageContext, String[] strFileType,
			int maxSize, String strUpFileUrl) {
		String uploadErr = "";
		SmartUpload smartUpload = new SmartUpload();
		try {
			System.out.println("1");
			smartUpload.initialize(pageContext);
			System.out.println("2");
			smartUpload.upload();
			System.out.println("3");
			for (int i = 0; i < smartUpload.getFiles().getCount(); i++) {
				com.jspsmart.upload.File myFile = smartUpload.getFiles().getFile(i);
				if (!myFile.isMissing()) {
					int fileSize = myFile.getSize();
					String strFileName = myFile.getFileName();
					String strExtName = myFile.getFileExt();

					if (uploadErr.equals("")
							&& !blInArray(strFileType, strExtName)) {
						uploadErr = "�ļ�" + strFileName + "���Ͳ���ȷ,�����ϴ�!";
					}

					if (uploadErr.equals("") && fileSize > maxSize * 1024) {
						uploadErr = strFileName + "��С����ȷ,�ļ����ܴ���"
								+ maxSize + "K!";
					}

					if (uploadErr.equals("")) {
						String fileName = System.currentTimeMillis() + "."
								+ strExtName;
						strUpFileUrl = strUpFileUrl + "/" + fileName;
						myFile.saveAs(strUpFileUrl, smartUpload.SAVE_VIRTUAL);

					} else {
						uploadErr = "��ѡ��Ҫ�ϴ����ļ�!";
					}

					if (!uploadErr.equals(""))
						break;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			uploadErr = "���������?!";
		}
		return uploadErr;
	}
}
